<?php

namespace app\admin\controller\qudao;

use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Validate;
use app\admin\model\caiwu\Money as moneylog;
use app\common\controller\MyHelp;

/**
 * 管理员管理
 *
 * @icon   fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Adminlist extends Backend
{

    /**
     * @var \app\admin\model\Admin
     */
    protected $model = null;
    protected $selectpageFields = 'id,username,nickname,avatar';
    protected $searchFields = 'id,username,nickname';
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $childrenGroupIds = $this->childrenGroupIds;

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('s_id', $this->auth->id)
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
                $row->visible(['username', 'id', 'money', 'nickname', 'avatar', 'mobile', 'createtime', 'money', 'alltx', 'status']);
            }
            // foreach ($list as $k => &$v) {
            // }
            // unset($v);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    if (!Validate::is($params['password'], '\S{6,30}')) {
                        exception(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = $this->auth->getEncryptPassword($params['password'], $params['salt']);
                    $params['api_token'] = md5(time() . '8523');
                    $params['key'] = substr(md5(time() . '8523'), 0, 16);
                    $params['avatar'] = 'http://cdn.8n888.cn/uploads/20231107/856947342dfb71db97f024a5ca2c430d.png'; //设置新管理员默认头像。
                    $params['s_id'] = $this->auth->id;
                    $result = $this->model->validate('Admin.add')->save($params);
                    if ($result === false) {
                        exception($this->model->getError());
                    }
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => 2]; //话费
                    model('AuthGroupAccess')->saveAll($dataset);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }

    public function priceset($ids)
    {
        $sku =  db::table('fa_hf_goods')->select();
        $admin = db::table('fa_admin')->where('id', $this->auth->id)->find();

        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');

            foreach ($sku as $key1 => $value1) {
                if (!isset($params['add' . $value1['id']])) {
                    return $this->error('参数有误');
                }
                $addrate = $params['add' . $value1['id']];
                // return  $addrate;
                if ($addrate < 0) {
                    return $this->error('金额必须大于0');
                }

                $zz =  db::table('fa_hf_goods_addprice')->where('admin_id', $ids)->where('goodsid', $value1['id'])->where('type', 2)->find();
                if ($zz) {
                    db::table('fa_hf_goods_addprice')->where('id', $zz['id'])->update(['add' => $addrate]);
                } else {
                    db::table('fa_hf_goods_addprice')->insert(['add' => $addrate, 'goodsid' => $value1['id'], 'admin_id' => $ids, 'type' => 2]);
                }
            }
            return $this->success('修改成功');
        }

        foreach ($sku as $key1 => $value1) {
            $zzzz =  MyHelp::getPriceNew($admin, $value1['id']); //直接推广者
            $myprice = $zzzz['price']; //成本价
            $zz =  db::table('fa_hf_goods_addprice')->where('admin_id', $ids)->where('goodsid', $value1['id'])->where('type', 2)->find();
            if ($zz) {
                $sku[$key1]['add'] = $zz['add'];
            } else {
                $sku[$key1]['add'] = 0;
            }
            $sku[$key1]['myprice'] = $myprice;
        }
        $this->assign('zz', $sku);
        return $this->view->fetch();
    }
}
